package wechat

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type TemplateCourseNoticeDataValue struct {
	Value string `json:"value"`
}

type TemplateCourseNoticeData struct {
	First    TemplateCourseNoticeDataValue `json:"first"`
	Keyword1 TemplateCourseNoticeDataValue `json:"keyword1"` // 课程学期
	Keyword2 TemplateCourseNoticeDataValue `json:"keyword2"` // 课程课时
	Keyword3 TemplateCourseNoticeDataValue `json:"keyword3"` // 课程安排
	Remark   TemplateCourseNoticeDataValue `json:"remark"`
}

type TemplateCourseNotice struct {
	Touser     string                   `json:"touser"`
	TemplateId string                   `json:"template_id"`
	Url        string                   `json:"url"`
	Data       TemplateCourseNoticeData `json:"data"`
}

type TemplateCourseNoticeRes struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Msgid   int64  `json:"msgid"`
}

// 发送课程通知
func SendCourseNotice(openid string, first string, remark string, url string,
	k1 string, k2 string, k3 string) {
	t := TemplateCourseNotice{
		Touser:     openid,
		TemplateId: beego.AppConfig.String("coursenoticeid"),
		Url:        url,
		Data: TemplateCourseNoticeData{
			First:    TemplateCourseNoticeDataValue{Value: first},
			Keyword1: TemplateCourseNoticeDataValue{Value: k1},
			Keyword2: TemplateCourseNoticeDataValue{Value: k2},
			Keyword3: TemplateCourseNoticeDataValue{Value: k3},
			Remark:   TemplateCourseNoticeDataValue{Value: remark},
		},
	}
	content, err := json.Marshal(t)
	if err != nil {
		logs.Error("can not marshal course notice struct:", err)
		return
	}
	ret := SendTemplateMsg("anban", string(content))
	res := TemplateCourseNoticeRes{}
	err = json.Unmarshal([]byte(ret), &res)
	if err != nil {
		logs.Error("can not unmarshal send course notice response:", err)
		return
	}
	if res.Errcode != 0 {
		logs.Error("send course notice fail:", res.Errmsg)
		return
	}
}
